package com.jfinal.plugin.avtivemq;

import javax.jms.JMSException;
import javax.jms.Session;
import java.util.concurrent.TimeUnit;

/**
 * @createTime: 2018/12/20
 * @author: HingLo
 * @description: 连接池工具
 */
public class SessionKit {
    /**
     * 获取session，默认等待10s,如果10s 任然没有获取到session就从创建一个session放入到连接池中
     *
     * @return 返回session
     * @throws InterruptedException
     */
    public static Session getJmsSession() throws InterruptedException, JMSException {
        // 启动链接
        Session session;
        if (ConnectFactory.getPoolSession().isEmpty()) {
            // 设置等待时间为10秒
            int max = 10;
            session = ConnectFactory.getPoolSession().poll(max, TimeUnit.MILLISECONDS);
            if (session == null) {
                session = ConnectFactory.getConnection().createSession(ConnectFactory.isTransacted(), ConnectFactory.getAcknowledgeMode());
            }
        } else {
            session = ConnectFactory.getPoolSession().poll();
        }
        return session;
    }

    /**
     * 消息发送结束后,需要将session放回到消息队列中,下次在用
     *
     * @param session session
     */
    public static void closed(Session session) {
        if (ConnectFactory.getPoolSession().size() < ConnectFactory.getMax()) {
            ConnectFactory.getPoolSession().add(session);
        } else {
            try {
                session.close();
            } catch (JMSException e) {
                System.out.println("session关闭错误，重新放入到连接池中利用");
                ConnectFactory.getPoolSession().add(session);
            }
        }
    }
}
